package BinaryTree;

import test0ne.TreeNode;

import java.util.Stack;

/**
 * @Author zhang lei
 * @Date 2021-11-22 18:42
 * @Description 二叉树遍历相关
 */
public class Algo_Offer47 {
    /**
     * 递归遍历二叉树
     * @param root
     */
    public void recursion(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.println(root.val);
        recursion(root.left);
        recursion(root.right);
    }

    /**
     * https://blog.csdn.net/canmengmeng/article/details/81328352
     * 非递归前序遍历
     * 栈  先入后出， 一个while循环 先放右节点，然后放入左节点
     */
    public static void preIter(TreeNode root) {
        if(root == null) {
            return;
        }

        Stack<TreeNode> s = new Stack<>();

        TreeNode cur = root;
        System.out.println(cur.val);
        s.push(cur);
        while (!s.isEmpty()) {
            TreeNode p = s.pop();
            System.out.println(p.val);

            if(p.right!=null) {
                s.push(p.right);
            }
            if(p.left!=null) {
                s.push(p.left);
            }
        }
    }

    /**
     * 中序遍历
     * @param root
     */
    public static void inIter(TreeNode root) {
        if(root == null) {
            return;
        }

        Stack<TreeNode> s = new Stack<>();

        s.push(root);
        while (!s.isEmpty()) {
            TreeNode p = s.pop();
            if(p.right!=null) {
                s.push(p.right);
            }
            s.push(p);
            if(p.left!=null) {
                s.push(p.left);
            }
        }

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        preIter(root);
    }
}
